//
//  DeBugPlugin.swift
//  SwiftProject
//
//  Created by 董駸 on 2022/7/28.
//

import Moya

/// 用于打印网络请求参数插件
class DeBugPlugin: PluginType {
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        // print("prepare")
        if DEBUG {
            print("请求接口：\(request.url!.absoluteString)" + " 方式：\(request.httpMethod!)")
            if let httpBody = request.httpBody {
                if let str = String(data: httpBody, encoding: .utf8) {
                    print("请求参数：\(str)")
                }
            }
            print("请求头：\(request.headers)")
        }
        return request
    }
    
    func willSend(_ request: RequestType, target: TargetType) {
        //print("开始请求")
    }
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        //print("结束请求")
        guard case let Result.failure(faildResponse) = result else {
            let response = try! result.get()
            let data = response.data
            guard let jsonDic = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any] else {
                return
            }
            if DEBUG {
                print("返回结果：\(jsonDic)")
            }
            return
        }
        //请求失败走的failure 方法
//        QMUITips.showError("请求失败：Code -\(faildResponse.errorCode)\n Reason -\(faildResponse.errorDescription!)")
    }
}
